<template>
  <view class="box">
    <!-- #ifdef MP-WEIXIN -->
    <view
      class="head"
      :style="
        'padding-top:' +
        statusBarHeight1 +
        'px;padding-right:' +
        (WXwidth + 15) +
        'px;height:' +
        (statusBarHeight1 + 44) +
        'px'
      "
    >
      <!-- #endif -->
      <!-- #ifndef MP-WEIXIN -->
      <view
        class="head"
        :style="
          'padding-top:' + (statusBarHeight1 + 10) + 'px;height:' + (statusBarHeight1 + 54) + 'px'
        "
      >
        <!-- #endif -->
        <image
          class="fanhui"
          @click="fanhui"
          src="https://pic.bangbangtongcheng.com/static/fanhui_bai.png"
          mode=""
        ></image>
        <view class="biaoti"> 兑换方式 </view>
        <view class="fanhui"></view>
      </view>
      <!-- #ifdef MP-WEIXIN -->
      <view
        :style="'padding-top:' + statusBarHeight1 + 'px;height:' + (statusBarHeight1 + 44) + 'px'"
      ></view>
      <!-- #endif -->
      <!-- #ifndef MP-WEIXIN -->
      <view
        :style="'padding-top:' + statusBarHeight1 + 'px;height:' + (statusBarHeight1 + 54) + 'px'"
      ></view>
      <!-- #endif -->
      <view class="table_top">
        <!-- <view :class="id ? 'iteam active' : 'iteam'">
					线下领取
					<image v-if="id" class="image" src="https://pic.bangbangtongcheng.com/static/xuanzhong.png"
						mode="widthFix" />
				</view>
				<view :class="!id ? 'iteam active' : 'iteam'">
					快递邮寄
					<image v-if="!id" class="image" src="https://pic.bangbangtongcheng.com/static/xuanzhong.png"
						mode="widthFix" />
				</view> -->
        <!-- 旧页面有误，后台配置中支持两种领取方式，故更改页面逻辑 -->
        <view
          v-for="item in tabList"
          :key="item.id"
          class="iteam"
          :class="{ active: item.show }"
          @click="changeTab(item)"
        >
          {{ item.name }}
          <image
            v-show="item.show"
            class="image"
            src="https://pic.bangbangtongcheng.com/static/xuanzhong.png"
            mode="widthFix"
          />
        </view>
      </view>
      <!-- 线下领取 -->
      <view class="offlineCollection" v-show="showTabId === '1'">
        <view class="QRCode">
          <image class="image" :src="codeImage" mode=""></image>
          <view class="spans"> 前往线下指定商家扫码领取 </view>
        </view>
        <view class="receivPlace">
          <view class="title"> 领取地点 </view>
          <scroll-view
            scroll-y="true"
            class="list"
            :style="'height: calc(100vh - ' + curTop + 'px );'"
            @scrolltolower="down"
          >
            <view
              class="giftList"
              v-for="(item, index) in Recommend"
              :key="index"
              @click="openMap(item)"
            >
              <image class="image" mode="aspectFit" :src="item.picture" />
              <view class="center">
                <view class="title">
                  <view class="mz">
                    {{ item.name }}
                  </view>
                  <image
                    class="images"
                    src="https://pic.bangbangtongcheng.com/static/bbcz/Navigation.png"
                    mode=""
                  ></image>
                </view>
                <view class="address">
                  {{ item.address }}
                </view>
                <view class="gift">
                  <view class="gift_left">
                    {{ item.giftName }}
                  </view>
                  <view class="gift_rigth"> 余量：{{ item.remainingInventory }} </view>
                </view>
              </view>
            </view>
            <view v-if="Recommend.length == 0" class="none">
              <image src="https://pic.bangbangtongcheng.com/static/none.png" mode="widthFix" />
              <view>没有更多数据了</view>
            </view>
            <view class="down" v-show="Recommend.length != 0 && !downStatus">没有更多了</view>
          </scroll-view>
        </view>
      </view>
      <!-- 快递邮寄 -->
      <view class="expressMail" v-show="showTabId === '2'">
        <view class="addressManagement" @click="addressChage()">
          <view class="title"> 地址管理 </view>
          <image
            class="image"
            src="https://pic.bangbangtongcheng.com/static/bbzc/recruitmentDetails/zp_05.png"
            mode=""
          ></image>
        </view>
        <view class="information">
          <view class="item">
            <view class="title"> 收货人 </view>
            <input class="input" v-model="addressData.consignee" type="text" />
          </view>
          <view class="item">
            <view class="title"> 手机号码 </view>
            <input class="input" maxlength="11" v-model="addressData.phoneNumber" type="number" />
          </view>
          <view class="item">
            <view class="title"> 所在地区 </view>
            <view class="inputs">
              {{ addressData.region }}
            </view>
            <!-- <input class="input" v-model="addressData.region" disabled type="text"> -->
          </view>
          <view class="detailAddress">
            <view class="title"> 详细地址 </view>
            <textarea
              class="input"
              v-model="addressData.detailedAddress"
              cols="30"
              rows="10"
            ></textarea>
          </view>
        </view>
        <view class="define" @click="affirm"> 确定 </view>
      </view>
      <uni-popup ref="binds" mode="center">
        <view class="binds_frame">
          <view class="binds_frame_t">兑换成功</view>
          <view class="binds_frame_c"
            >请耐心等待快递上门，快递单号将在信息通知中心发给您，请注意查收。</view
          >
          <view class="binds_frame_b">
            <!-- <view class="cancel" @click="jcbdCancel">取消</view> -->
            <view class="determine" @click="fanhui">我知道了</view>
          </view>
        </view>
      </uni-popup>
      <uniBall></uniBall>
    </view>
  </view>
</template>
<script>
  import permision from '@/js_sdk/wa-permission/permission.js'
  //#ifdef H5
  import wxshare from '@/utils/index.js'
  //#endif
  import { mapGetters } from 'vuex'
  export default {
    data() {
      return {
        userInfo: uni.getStorageSync('Pduser'),
        WXwidth: '',
        pageSize: 10,
        pageNo: 1,
        Recommend: [],
        trigger: false,
        downStatus: true,
        upStatus: true,
        latitude: '',
        longitude: '',
        curTop: 300,
        codeImage: '',
        id: '',
        giftId: '',
        // 邮寄信息
        sendByPost: {},
        addressData: {},
        tabList: [],
        showTabId: '',
      }
    },
    onLoad(options) {
      var than = this
      // #ifdef MP-WEIXIN
      // 获取胶囊信息
      let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
      let getWindowInfo = uni.getWindowInfo().screenWidth
      this.WXwidth = getWindowInfo - (menuButtonInfo.right - menuButtonInfo.width)
      // #endif
      // 获取活动详情传递过来的信息
      if (options.id) {
        // 当有这个id时，必定是线下扫码兑换
        this.id = options.id
        this.giftId = options.giftId
        this.obtainGiftQRCode()
      } else {
        this.sendByPost = uni.getStorageSync('yjlp_key')
        uni.removeStorageSync('yjlp_key')
        this.initTabList()
      }
      /* #ifdef H5 */
      this.jinzhi()
      /* #endif */
    },
    onShow() {
      this.defaultAddress()
      // this.id && this.getLocation()
      if (uni.getStorageSync('locationState') == 1 && this.id) {
        this.getLocation()
      }
    },
    methods: {
      initTabList() {
        const arr = [
          {
            name: '线下领取',
            id: '1',
            show: false,
          },
          {
            name: '快递邮寄',
            id: '2',
            show: false,
          },
        ]
        if (!this.sendByPost.exchangeMethod) return false
        const newArr = arr.filter((v) => this.sendByPost.exchangeMethod.indexOf(v.id) >= 0)
        this.tabList = newArr
        this.changeTab(newArr[0])
      },
      changeTab(item) {
        this.showTabId = item.id
        this.tabList.forEach((v) => {
          v.show = v.id === item.id
        })
        if (item.id === '1' && !this.codeImage) {
          this.obtainGiftQRCode()
          this.getLocation()
        }
      },
      // 获取礼品二维码
      obtainGiftQRCode() {
        this.$myRequest
          .get('/api/mobile/public/getClaimQRCode', {
            exchangeRecordsId: this.id,
            userId: this.userInfo.id,
            giftId: this.sendByPost.giftId,
            colour: 1,
            width: 540,
            height: 540,
          })
          .then((res) => {
            this.codeImage = res.codeImages
          })
      },
      // 获取默认地址
      defaultAddress() {
        this.$myRequest
          .get('/api/mobile/public/getDefaultHarvestAddress', {
            userId: this.userInfo.id,
          })
          .then((res) => {
            this.addressData = res.defaultHarvestAddress || {}
          })
      },
      async affirm() {
        let that = this
        let obj = this.sendByPost
        if (!this.addressData.id) {
          uni.showToast({
            title: '暂无地址，请前往地址管理中添加地址！',
            icon: 'none',
            mask: true,
          })
          return false
        }
        obj.consignee = this.addressData.consignee
        obj.phoneNumber = this.addressData.phoneNumber
        obj.region = this.addressData.region
        obj.detailedAddress = this.addressData.detailedAddress
        const tabItem = this.tabList.find((v) => v.show)
        tabItem && (obj.exchangeMethod = tabItem.id)
        this.$myRequest.post('/api/mobile/public/addExchangeRecords', obj).then((res) => {
          /* success 则是兑换成功，失败使用提示即可 */
          if (res.success) {
            this.giftStatusChange(res.ExchangeRecordsId)
            this.$refs.binds.open()
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none',
              mask: true,
            })
          }
          // setTimeout(()=>{
          // 	that.fanhui()
          // },500)
        })
      },
      async giftStatusChange(id) {
        const res = await this.$myRequest.post('/api/mobile/public/confirmRedemption', {
          userId: this.userInfo.id,
          id,
        })
      },
      addressChage() {
        uni.navigateTo({
          url: '/pages_my/addressManagement',
        })
      },
      down() {
        if (this.downStatus) {
          this.pageNo++
          this.getRecommend()
        }
      },
      async up() {
        this.Recommend = []
        this.pageNo = 1
        this.downStatus = true
        if (this.upStatus) {
          this.trigger = true
          await this.getRecommend()
        }
      },
      getRecommend() {
        let that = this
        this.upStatus = false
        this.$myRequest
          .get('/api/mobile/public/getCollectionLocationTabulation', {
            giftId: this.sendByPost.giftId,
            pageSize: this.pageSize,
            pageNo: this.pageNo,
            longitude: this.longitude,
            latitude: this.latitude,
          })
          .then((res) => {
            uni.hideLoading()
            if (!res.collectionLocationTabulation.pageList.length) {
              this.downStatus = false
            }
            if (res.collectionLocationTabulation.pageCount < this.pageNo * this.pageSize) {
              this.downStatus = false
            }
            this.upStatus = true
            this.trigger = false
            this.Recommend = this.Recommend.concat(res.collectionLocationTabulation.pageList)
            uni.stopPullDownRefresh()
            this.$nextTick(function () {
              uni
                .createSelectorQuery()
                .in(this)
                .select('.list')
                .boundingClientRect((result) => {
                  if (result) {
                    that.curTop = result.top
                  }
                })
                .exec()
            })
          })
      },
      jinzhi() {
        let _this = this
        let param = window.location.href.split('#')[0]
        uni.request({
          method: 'post',
          data: {
            url: param,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded',
          },
          url: 'https://www.bangbangtongcheng.com/conven//mob/login/getJsTicket.do',
          success(re) {
            _this.jinzhifx(re.data)
          },
        })
      },
      jinzhifx(data) {
        wxshare.config({
          debug: false, //是否打开调试
          appId: data.appId, // 公众号的唯一标识
          timestamp: data.timestamp, // 生成签名的时间戳
          nonceStr: data.nonce, // ，生成签名的随机串
          signature: data.signature, // 签名
          jsApiList: ['hideMenuItems'],
        })
        // 禁止分享
        wxshare.hideMenuItems({
          // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
          menuList: [
            'menuItem:share:appMessage',
            'menuItem:share:timeline',
            'menuItem:share:timeline',
            'menuItem:share:qq',
            'menuItem:favorite',
            'menuItem:share:QZone',
            'menuItem:openWithSafari',
          ],
        })
      },
      // 获取位置
      async getLocation() {
        this.getLocation1()
      },
      getLocation1() {
        let _this = this
        uni.showLoading({
          title: '加载中',
          mask: true,
        })
        uni.getLocation({
          type: 'gcj02',
          highAccuracyExpireTime: '3000',
          success(res) {
            _this.latitude = res.latitude
            _this.longitude = res.longitude
            _this.getRecommend()
          },
          fail:(res) => {
            console.log(res, '经纬度没有授权');
            this.$SHOWMODAL_TO_SETTINGS();
            uni.hideLoading()
            uni.setStorageSync('locationState', 0)
            if (uni.getStorageSync('locationState') == 0) {
              // uni.showModal({
              //   title: '提示',
              //   content: '您已关闭位置权限或获取位置信息失败',
              //   success: function (res) {
              //     if (res.confirm) {
              //       // plus.runtime.openURL("app-settings:");
              //       if (plus.os.name === 'iOS') {
              //         plus.runtime.openURL('app-settings://')
              //       } else {
              //         var Intent = plus.android.importClass('android.content.Intent')
              //         var Settings = plus.android.importClass('android.provider.Settings')
              //         var Uri = plus.android.importClass('android.net.Uri')
              //         var mainActivity = plus.android.runtimeMainActivity()
              //         var intent = new Intent()
              //         intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
              //         var uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
              //         intent.setData(uri)
              //         mainActivity.startActivity(intent)
              //       }
              //     } else if (res.cancel) {
              //       console.log('用户点击取消')
              //     }
              //   },
              // })
              return false
            }
          },
        })
      },
      fanhui() {
        uni.navigateBack({
          delta: 1,
        })
      },
      openMap(item) {
        let that = this
        /* #ifdef H5 */
        let param = window.location.href.split('#')[0]
        uni.request({
          method: 'post',
          data: {
            url: param,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded',
          },
          url: 'https://www.bangbangtongcheng.com/conven//mob/login/getJsTicket.do',
          success(re) {
            // var longitude = latitude;
            // var latitude = latitude;
            // that.setWxShare(re.data)
            uni.hideLoading()
            wxshare.config({
              debug: false, //是否打开调试
              appId: re.data.appId, // 公众号的唯一标识
              timestamp: re.data.timestamp, // 生成签名的时间戳
              nonceStr: re.data.nonce, // ，生成签名的随机串
              signature: re.data.signature, // 签名
              jsApiList: ['openLocation'],
            })
            wxshare.ready(function () {
              wxshare.openLocation({
                latitude: Number(item.latitude), //目的地latitude
                longitude: Number(item.longitude), //目的地longitude
                name: item.name,
                address: item.address,
                scale: 15, //地图缩放大小，可根据情况具体调整
              })
            })
          },
        })
        /* #endif */
        /* #ifndef H5 */
        uni.openLocation({
          latitude: Number(item.latitude),
          longitude: Number(item.longitude),
          name: item.name,
          address: item.address,
          success: function () {
            console.log('success')
          },
        })
        /* #endif */
      },
    },
    computed: {
      ...mapGetters(['userid', 'islogin', 'statusBarHeight1', 'userinfo']),
    },
  }
</script>
<style lang="less" scoped>
  .box {
    width: 100%;
    min-height: 100vh;
    background-color: #fff;
  }

  .head {
    position: fixed;
    top: 0;
    left: 0;
    width: 750rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
    background-color: #64b6a8;
    z-index: 1000;
    color: #fff;

    .fanhui {
      width: 40rpx;
      height: 40rpx;
    }
    .biaoti {
      font-size: 36rpx;
      font-weight: 500;
    }
  }

  .table_top {
    width: 750rpx;
    height: 100rpx;
    box-shadow: 0px 1px 6rpx 1px rgba(201, 201, 201, 0.21);
    border: 1px solid rgba(222, 222, 222, 0.25);
    display: flex;
    align-items: center;

    .iteam {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      font-weight: 400;
      color: #aaa;

      .image {
        width: 50rpx;
        height: 24rpx;
      }
    }

    .active {
      color: #64b6a8;
    }
  }

  .offlineCollection {
    .QRCode {
      height: 540rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .image {
        width: 300rpx;
        height: 300rpx;
      }

      .spans {
        font-size: 28rpx;
        font-weight: 400;
        color: #888888;
        margin-top: 18rpx;
      }
    }

    .receivPlace {
      padding: 0 40rpx;

      .title {
        font-size: 30rpx;
        font-weight: 400;
        color: #333333;
        margin-bottom: 14rpx;
      }
      .giftList {
        display: flex;
        align-items: center;
        padding: 24rpx 0;
        border-bottom: 1px solid #e0e0e0;
        .image {
          width: 300rpx;
          height: 200rpx;
          border-radius: 20rpx;
          background-color: #f8f8f8;
          margin-right: 20rpx;
        }
        .center {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .mz {
              font-size: 30rpx;
              font-weight: 400;
              color: #333333;
            }
            .images {
              width: 40rpx;
              height: 40rpx;
            }
          }
          .address {
            font-size: 24rpx;
            font-weight: 400;
            color: #333333;
          }
          .gift {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .gift_left {
              font-size: 28rpx;
              font-weight: 400;
              color: #333333;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
            .gift_rigth {
              font-size: 28rpx;
              font-weight: 400;
              color: #333333;
            }
          }
        }
      }
      .giftList:last-child {
        border-bottom: none;
      }
    }
  }

  .expressMail {
    margin-top: 20rpx;
    padding: 0 50rpx;
    .addressManagement {
      width: 650rpx;
      height: 60rpx;
      background-color: #f2f2f2;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 30rpx;
      margin-bottom: 20rpx;
      .title {
        font-size: 30rpx;
        font-weight: 400;
        color: #333333;
      }
      .image {
        width: 50rpx;
        height: 50rpx;
      }
    }
    .information {
      .item {
        display: flex;
        align-items: center;
        margin-bottom: 18rpx;
        .title {
          flex: 1;
          font-size: 30rpx;
          font-weight: 400;
          color: #333333;
          margin-right: 10rpx;
        }
        .input {
          width: 520rpx;
          height: 60rpx;
          border-bottom: 1px solid #e0e0e0;
          padding: 0 10rpx;
        }
        .inputs {
          width: 520rpx;
          border-bottom: 1px solid #e0e0e0;
          padding: 0 10rpx;
        }
      }
      .detailAddress {
        display: flex;
        .title {
          font-size: 30rpx;
          font-weight: 400;
          color: #333333;
          margin-right: 10rpx;
        }
        .input {
          padding: 10rpx;
          width: 520rpx;
          height: 214rpx;
          border: 1px solid #e0e0e0;
        }
      }
    }
    .define {
      position: fixed;
      bottom: 200rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 670rpx;
      height: 80rpx;
      background-color: #64b6a8;
      border-radius: 50rpx;
      font-size: 34rpx;
      font-weight: 400;
      color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .down {
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
  }

  .none {
    text-align: center;

    image {
      width: 430rpx;
      margin-bottom: 16rpx;
    }

    view {
      height: 40rpx;
      line-height: 40rpx;
      color: #666;
    }
  }
  .binds_frame {
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 10rpx;
    text-align: center;
    .binds_frame_t {
      font-size: 36rpx;
      font-weight: 550;
      color: #000000;
      padding: 0 46rpx;
      padding-top: 36rpx;
    }
    .binds_frame_c {
      width: 500rpx;
      margin: 0 auto;
      font-size: 30rpx;
      font-weight: 400;
      color: #64b6a8;
      margin-top: 30rpx;
      margin-bottom: 50rpx;
    }
    .binds_frame_b {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .determine {
        flex: 1;
        height: 90rpx;
        border-radius: 0 10rpx 10rpx 0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        font-weight: 400;
        color: #fff;
        background-color: #64b6a8;
      }
    }
  }
</style>
